﻿using System;
using System.Diagnostics;
using System.IO;
using Newtonsoft.Json;
using Quartz;
using Quartz.Core;
using Quartz.Util;
using ZilLion.Core.Log;
using ZilLion.TaskManager.Core.Infrastructure;
using ZilLion.TaskManager.Entity.Entity;

namespace ZilLion.TaskManager.Core.Quartz
{
    public class ExeJob : IJob
    {
        public void Execute(IJobExecutionContext context)
        {
            if (context?.JobDetail?.JobDataMap != null)
            {
                var config = context.JobDetail.JobDataMap.TryGetAndReturn("taskconfig") as TaskConfig;
                var arguments =JsonConvert.SerializeObject(config).EncodeBase64();
#if DEBUG
                string taskjson = arguments.DecodeBase64();
                var testconfig = JsonConvert.DeserializeObject<TaskConfig>(taskjson );

#endif

                if (arguments.Length > 8000)
                {

                    CustomTaskLogger.Print(new Exception("TaskConfig序列化后超过8000字符"),"向EXE容器传参出错");
                    return;
                }
                var exep = new Process
                {
                    StartInfo =
                    {
                        FileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TaskRunnerConsole.exe"),
                        Arguments =arguments  ,
                        CreateNoWindow = true,
                        UseShellExecute = false
                    }
                };
                exep.Start();
                exep.WaitForExit(); //关键，等待外部程序退出后才能往下执行
                if (!exep.HasExited)
                {
                    exep.Kill();
                }

            }
        }
    }
}